package com.wzk.travelspringboot.config;

import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.errors.MinioException;
import io.minio.messages.Bucket;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;

/**
 * @Author: WangZiKang
 * @Date: 2025/1/7 21:24
 */
@Slf4j
@Configuration
public class MinioConfig {

    @Value("${minio.url}")
    private String url;
    @Value("${minio.username}")
    private String username;
    @Value("${minio.password}")
    private String password;
    @Value("${minio.bucketName}")
    private String bucketName;

    @Bean
    public MinioClient minioClient() throws MinioException {
        try{
            MinioClient minioClient = MinioClient.builder().endpoint(url)
                    .credentials(username, password).build();
            // 检查桶是否存在
            boolean isExist = false;
            List<Bucket> buckets = minioClient.listBuckets();
            for (Bucket bucket : buckets) {
                if (bucket.name().equals(bucketName)) {
                    isExist = true;
                    break;
                }
            }
            // 如果桶不存在则创建
            if (!isExist) {
                // 创建桶
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            }
            return minioClient;
        }catch (Exception e){
            throw new MinioException("初始化minioClient失败!"+e);
        }
    }


}
